﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.PropertyManage.Controllers
{
    public class CS_RepaireBillController : MvcControllerBase
    {
        private RepaireBLL bll = new RepaireBLL();
        private DataItemBLL dataitemBLL = new DataItemBLL();
        private DataItemDetailBLL dataitemdetailBLL = new DataItemDetailBLL();
        private static HttpFileCollection hfc;
        #region 视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Form()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Detail()
        {
            ViewBag.Mode = new CodeRuleBLL().CheckBillCodeMode(((int)CodeRuleEnum.RepaireCode).ToString());
            return View();
        }
        #endregion

        #region 获取数据
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取树", "GetList")]
        private List<TreeStatusEntity> GetList(string queryJson)
        {
            DataTable dt = bll.GetCountList(queryJson);
            List<TreeStatusEntity> li = new List<TreeStatusEntity>();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName == "all")
                        li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(RStateEnum.All), RStateEnum.All.ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "uncomplete")
                        li.Add(new TreeStatusEntity(RStateEnum.All.ToString(), EnumAttribute.GetDescription(RStateEnum.UnComplete), ((int)RStateEnum.UnComplete).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "unsend")
                        li.Add(new TreeStatusEntity(((int)RStateEnum.UnComplete).ToString(), EnumAttribute.GetDescription(RStateEnum.UnSend), ((int)RStateEnum.UnSend).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "sending")
                        li.Add(new TreeStatusEntity(((int)RStateEnum.UnComplete).ToString(), EnumAttribute.GetDescription(RStateEnum.Sending), ((int)RStateEnum.Sending).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "unrepairing")
                        li.Add(new TreeStatusEntity(((int)RStateEnum.UnComplete).ToString(), EnumAttribute.GetDescription(RStateEnum.UnRepairing), ((int)RStateEnum.UnRepairing).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "repairing")
                        li.Add(new TreeStatusEntity(((int)RStateEnum.UnComplete).ToString(), EnumAttribute.GetDescription(RStateEnum.Repairing), ((int)RStateEnum.Repairing).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "completed")
                        li.Add(new TreeStatusEntity(RStateEnum.All.ToString(), EnumAttribute.GetDescription(RStateEnum.Completed), ((int)RStateEnum.Completed).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "unreturnback")
                        li.Add(new TreeStatusEntity(((int)RStateEnum.Completed).ToString(), EnumAttribute.GetDescription(RStateEnum.UnReturnBack), ((int)RStateEnum.UnReturnBack).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "repaired")
                        li.Add(new TreeStatusEntity(((int)RStateEnum.Completed).ToString(), EnumAttribute.GetDescription(RStateEnum.Repaired), ((int)RStateEnum.Repaired).ToString(), dt.Rows[0][i].ToInt()));

                    else if (dt.Columns[i].ColumnName == "returnbill")
                        li.Add(new TreeStatusEntity(StateEnum.All.ToString(), EnumAttribute.GetDescription(RStateEnum.ReturnBill), ((int)RStateEnum.ReturnBill).ToString(), dt.Rows[0][i].ToInt()));
                    else if (dt.Columns[i].ColumnName == "cancelbill")
                        li.Add(new TreeStatusEntity(StateEnum.All.ToString(), EnumAttribute.GetDescription(RStateEnum.CancelBill), ((int)RStateEnum.CancelBill).ToString(), dt.Rows[0][i].ToInt()));
                    else
                        continue;
                }
            }
            return li;
        }

        /// <summary>
        /// 获取单据状态树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取单据状态树", "GetStateTreeList")]
        public ActionResult GetStateTreeList(string queryJson)
        {
            var data = GetList(queryJson);
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (TreeStatusEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.PValue == item.Value) == 0 ? false : true;
                tree.id = item.Value;
                tree.text = item.Text + "<" + item.Count + ">";
                tree.value = item.Value;
                if (item.PValue == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.PValue;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        /// <summary>
        /// 分页查询列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "分页查询列表", "GetPageListJson")]
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["OrganizeId"].IsEmpty())
            {
                queryParam["PStructIds"] = new PStructCache().GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                queryJson = queryParam.ToJson();
            }
            var data = bll.GetPageList(pagination, queryJson);
            //if (!OperatorProvider.Provider.Current().IsSystem)
            //{
            //    var s1 = new TaskUserBLL().GetList().Where(t => t.UserId == OperatorProvider.Provider.Current().UserId);
            //    var s2=new TaskBLL().GetList().Where(t => t.Category == 3).ToList();
            //    if (s1 != null&&s1.Count()>0&&s2!=null&&s2.Count()>0)
            //    {
            //        var ss = (from a in s1 join b in s2 on a.TaskId equals b.Id select new { b.SourceId }).Distinct();
            //        string str =ss!=null? string.Join(",", ss):"";
            //        data = data.Where(t => t.CreateUserId == OperatorProvider.Provider.Current().UserId || str.Contains(t.Id));
            //    }
            //    else
            //    {
            //        data = data.Where(t => t.CreateUserId == OperatorProvider.Provider.Current().UserId);
            //    }

            //}
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetForm, "获取实体", "GetFormJson")]
        public ActionResult GetFormJson(string keyValue)
        {
            var obj1 = bll.GetEntity(keyValue);
            var obj2 = bll.GetDetailEntity(keyValue);
            string BillId = obj1.SourceType == 2 ? keyValue + "," + obj1.SourceId : keyValue;
            var file = new AttachFileBLL().GetList(BillId);
            var task = new SysTaskBLL().GetList().Where(t => t.SourceId == obj1.Id);
            var Worker = new AccountBLL().GetEntityByAccount(OperatorProvider.Provider.Current().Account).SourceId;
            var taskSend = task != null ? task.FirstOrDefault(t => t.Type == 2) : null;
            var IsSendWay = taskSend == null ? false : new TaskUserBLL().ValidateUser(taskSend.Id, Worker) ? true : false;
            var taskDispose = task != null ? task.FirstOrDefault(t => t.State < 3 && t.Type == 1) : null;
            var IsDispose = taskDispose == null ? false : new TaskUserBLL().ValidateUser(taskDispose.Id, Worker) ? true : false;
            var taskReturn = task != null ? task.FirstOrDefault(t => t.State < 3 && t.Type == 3) : null;
            var IsReturn = taskReturn == null ? false : new TaskUserBLL().ValidateUser(taskReturn.Id, Worker) ? true : false;
            var jsonData = new
            {
                data1 = obj1,
                data2 = obj2,
                data3 = file,
                IsSendWay = IsSendWay,
                IsDispose = IsDispose,
                IsReturn = IsReturn
            };
            return Content(jsonData.ToJson());
        }
        /// <summary>
        /// 维修专业
        /// </summary>
        /// <returns>返回树型结构</returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取维修专业树", "GetMajorTreeJson")]
        public ActionResult GetMajorTreeJson()
        {
            var itemId = dataitemBLL.GetEntity("", "维修专业").ItemId;
            var data = dataitemdetailBLL.GetList(itemId);
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (DataItemDetailEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ItemDetailId == item.ParentId) == 0 ? false : true;
                tree.id = item.ItemDetailId;
                tree.text = item.ItemName;
                tree.value = item.ItemValue;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.ParentId;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        #endregion

        #region
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="repaireBillEntity"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存维修", "SaveForm")]
        public ActionResult SaveForm(string keyValue, RepairBillEntity repaireBillEntity, RepairBillDetailEntity repairBillDetailEntity)
        {
            List<AttachFileEntity> listFile = new List<AttachFileEntity>();
            try
            {
                string URL = Request.Url.ToString().Replace(Request.RawUrl, "/");
                string imgPath = "/Resource/RepairBillFile_" + OperatorProvider.Provider.Current().CustomerCode + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                if (hfc != null && hfc.Count > 0)
                {
                    for (int i = 0; i < hfc.Count; i++)
                    {
                        if (hfc[i].FileName == "") continue;
                        else
                        {
                            AttachFileEntity AttachFileEntity = new AttachFileEntity();
                            AttachFileEntity.Create();
                            AttachFileEntity.Category = 3;
                            AttachFileEntity.Type = 31;
                            AttachFileEntity.TypeName = "报修附件";
                            AttachFileEntity.FileName = hfc[i].FileName;
                            string FilePath = Server.MapPath(imgPath);
                            if (!Directory.Exists(FilePath))
                            {
                                Directory.CreateDirectory(FilePath);
                            }
                            hfc[i].SaveAs(FilePath + hfc[i].FileName);
                            AttachFileEntity.FileUrl = URL != "" ? FilePath.Replace(HttpRuntime.AppDomainAppPath, URL) + hfc[i].FileName : FilePath + hfc[i].FileName;
                            listFile.Add(AttachFileEntity);

                        }

                    }
                }
                bll.SaveForm(keyValue, repaireBillEntity, repairBillDetailEntity, listFile);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存维修", "SaveFormTest")]
        public ActionResult SaveFormTest(string keyValue, RepairBillEntity repaireBillEntity, RepairBillDetailEntity repairBillDetailEntity, string IMG)
        {
            List<AttachFileEntity> listFile = new List<AttachFileEntity>();
            try
            {
                List<Object> lst = IMG.ToObject<List<Object>>();
                string URL = Request.Url.ToString().Replace(Request.RawUrl, "/P");
                string SRC = URL.Substring(0, URL.IndexOf("/P"));
                string imgPath = "/Resource/RepairBillFile" + OperatorProvider.Provider.Current().CustomerCode + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                foreach (var item in lst)
                {
                    var queryParam = item.ToString().ToJObject();
                    int ImgType = queryParam["Type"].ToInt();
                    string Name = queryParam["Name"].ToString();
                    AttachFileEntity AttachFileEntity = new AttachFileEntity();
                    AttachFileEntity.Create();
                    AttachFileEntity.FileName = Name;
                    string FilePath = Server.MapPath(imgPath);
                    AttachFileEntity.FileUrl = FilePath.Replace(HttpRuntime.AppDomainAppPath, SRC + "/") + Name;
                    if (!keyValue.IsEmpty() && ImgType == 2)
                    {
                        AttachFileEntity.Category = 3;
                        AttachFileEntity.Type = 32;
                        AttachFileEntity.TypeName = "维修完成附件";
                        listFile.Add(AttachFileEntity);
                    }
                    if (keyValue.IsEmpty() && ImgType == 1)
                    {
                        AttachFileEntity.Category = 3;
                        AttachFileEntity.Type = 31;
                        AttachFileEntity.TypeName = "报修附件";
                        listFile.Add(AttachFileEntity);
                    }
                }
                bll.SaveForm(keyValue, repaireBillEntity, repairBillDetailEntity, listFile);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Delete, "保存维修", "SaveFormTest")]
        public ActionResult RemoveForm(string keyValue)
        {
            bll.RemoveForm(keyValue);
            return Success("删除成功。");
        }
        #endregion

        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Other, "上传文件", "UploadFile")]
        public ActionResult UploadFile1()
        {

            hfc = System.Web.HttpContext.Current.Request.Files;
            string imgPath = "/Resource/RepairBillFile" + OperatorProvider.Provider.Current().CustomerCode + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            if (hfc != null && hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    string FilePath = Server.MapPath(imgPath);
                    if (!Directory.Exists(FilePath))
                    {
                        Directory.CreateDirectory(FilePath);
                    }
                    hfc[i].SaveAs(FilePath + hfc[i].FileName);
                }
            }
            return Success("操作成功。");

        }


    }
}
